package org.example.management.service.impl;


import lombok.extern.slf4j.Slf4j;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.io.IOUtils;
import org.example.management.entity.GoodsEntity;
import org.example.management.service.ICreatHtmlService;
import org.example.remote.service.IUploadRemoteService;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;


@Service
@Slf4j
public class CreatHtmlServiceImpl implements ICreatHtmlService {

    @Autowired
    IUploadRemoteService upload;

    @Autowired
    private TemplateEngine templateEngine;

    @RabbitListener(queues = "promo_info")
    @Override
    //监听MQ队列 生成html文件并远程上传到静态资源服务器
    public void createAllHtml(GoodsEntity parse) {

            Context context=new Context();
            HashMap<String,Object> param=new HashMap<>();

            param.put("goods", parse);
            context.setVariables(param);

            String html = templateEngine.process("goods", context);

            FileItemFactory factory = new DiskFileItemFactory();
            DiskFileItem item = (DiskFileItem) factory.createItem("html", MediaType.APPLICATION_OCTET_STREAM_VALUE, true, String.valueOf(parse.getGoodsCode()));

            try(ByteArrayInputStream byteArrayInputStream=new ByteArrayInputStream(html.getBytes(StandardCharsets.UTF_8));
                OutputStream outputStream = item.getOutputStream())
            {
                IOUtils.copy(byteArrayInputStream,outputStream);
                MultipartFile uploadFile = new CommonsMultipartFile(item);
                upload.saveSecKillHtml(uploadFile, String.valueOf(parse.getGoodsCode()));
            } catch (IOException e) {
                log.error("{}文件生成失败",parse);
                throw new RuntimeException(e);
            }


    }

}
